import requests
from bs4 import BeautifulSoup
import random
import csv
import time
import socket
import http.client

def get_url(city_name):
    url = 'http://www.weather.com.cn/weather/'
    with open(r'C:\Users\Administrator\Desktop\djy.txt','r',encoding='utf-8') as f:
        lines = f.readlines()
        for line in lines:
            if (city_name in line):
                code = line.split('=')[0].strip()
                return url + code + '.shtml'
    raise ValueError('invalid city name')

def get_content(url,data=None):
    header = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, sdch',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.235'
    }
    timeout = random.choice(range(80,180))
    while True:
        try:
            # 获取请求数据
            rep = requests.get(url, headers=header, timeout=timeout)
            rep.encoding = 'utf-8'
            break
        except socket.timeout as e:
            print('3:', e)
            time.sleep(random.choice(range(8, 15)))
        except socket.error as e:
            print('4:', e)
            time.sleep(random.choice(range(20, 60)))
        except http.client.BadStatusLine as e:
            print('5:', e)
            time.sleep(random.choice(range(30, 80)))
        except http.client.BadStatusLine as e:
            print('6:', e)
            time.sleep(random.choice(range(5, 15)))
    return rep.text

def get_data(html_text,city_name):
    final = []
    t = []
    t.append(city_name)
    final.append(t)
    soup = BeautifulSoup(html_text, 'html.parser')  # 指定BeautifulSoup的解释器为 ‘html.parser’
    body = soup.body  # 获取，body部分
    data = body.find('div', {'id': '7d'})  # 找到id为7d的 div
    ul = data.find('ul')  # 找到ul的部分
    li = ul.find_all('li')  # 获取所有的li

    for day in li:  # 对每个li中的内容进行便利
        temp = []  # 代存每日数据
        data = day.find('h1').string  # 找到日期
        temp.append(data)  # 添加到 temp 中

        inf = day.find_all('p')  # 找到天气状态
        temp.append(inf[0].string)
        # 添加最高温
        if inf[1].find('spam') is None:  # 如果没有最高温
            highest = None  # 就没有
        else:
            highest = inf[1].find('span').string  # 如果有就找到最高温
            highest = highest.replace('℃', '')  # 去掉 ℃
        temp.append(highest)  # 将最高温添加到temp中
        # 添加最低温度
        lowest = inf[1].find('i').string  # 找到最低温度
        lowest = lowest.replace('℃', '')  # 去掉 ℃
        temp.append(lowest)  # 将最低温度添加到temp中
        final.append(temp)
    return final

def write_data(city_name,data,file_name):
    with open(file_name,'a',errors='ignore',newline='') as fs:
        f_csv = csv.writer(fs)
        f_csv.writerows(data)
        print('%s 天气已添加成功' % city_name)

if __name__ == '__main__':
    cities = input('请输入城市名（一个或者多个，以空格隔开）：').split(' ')
    for city in cities:
        url = get_url(city)
        html = get_content(url)
        result = get_data(html,city)
        write_data(city,result,r'C:\Users\Administrator\Desktop\djy.csv')






















